#include "stdafx.h"

HDC Map::mhdc;

Map::Map()
{
	wall = new Wall(mhdc, L"img\\wall.png");
	steel = new Steel(mhdc, L"img\\steel.png");
	water = new Water(mhdc, L"img\\water.png");
	//grass=new Grass(mhdc,L"")
}

Map::~Map()
{
	delete wall;
	delete steel;
	delete water;
}

Map * Map::getInstance()
{
	static Map m;

	return &m;
}

void Map::setHDC(HDC hdc)
{
	mhdc = hdc;
}

Wall * Map::getWall()
{
	return wall;
}

Steel * Map::getSteel()
{
	return steel;
}

Water * Map::getWater()
{
	return water;
}

bool Map::collide(Rect rc)
{
	return steel->collide(rc) || water->collide(rc) || wall->collide(rc);
}

bool Map::collide(Point pt)
{
	return steel->collide(pt) || water->collide(pt) || wall->collide(pt);
}

Point Map::getVacant(int width, int height)
{
	int x, y;

	for (int i = 0; i < 10; i++)
	{
		x = rand() % WIDTHMAP + LEFTMAP;
		y = rand() % HEIGHTMAP + TOPMAP;

		if (!collide({ x,y }))
		{
			return { x,y };
		}
	}

	return { -1,-1 };
}

void Map::set(rapidxml::xml_node<wchar_t> * mapnode)
{
	rapidxml::xml_node<wchar_t> * wallnode = mapnode->first_node();
	rapidxml::xml_node<wchar_t> * line = wallnode->first_node();

	/*int y = XMAP - 1;
	while (line)
	{
		int l = _wtoi(line->value());

		int x = 0;
		for (int i = 0; i < XMAP; i++)
		{
			wall->set(x, y--, l % 2);
			l /= 2;
		}

		x++;
		line = line->next_sibling();
	}*/

	for (int i = 0; i < YMAP; i++)
	{
		int l;

		if (line)
		{
			l = _wtoi(line->value());
			line = line->next_sibling();
		}
		else
		{
			l = 0;
		}

		for (int j = 0; j < XMAP; j++)
		{
			wall->set(XMAP - j - 1, i, l % 2);
			l /= 2;
		}
	}
	wall->update();

	wallnode = wallnode->next_sibling();
	line = wallnode->first_node();

	for (int i = 0; i < YMAP; i++)
	{
		int l;

		if (line)
		{
			l = _wtoi(line->value());
			line = line->next_sibling();
		}
		else
		{
			l = 0;
		}

		for (int j = 0; j < XMAP; j++)
		{
			steel->set(XMAP - j - 1, i, l % 2);
			l /= 2;
		}
	}
	steel->update();

	wallnode = wallnode->next_sibling();
	line = wallnode->first_node();

	for (int i = 0; i < YMAP; i++)
	{
		int l;

		if (line)
		{
			l = _wtoi(line->value());
			line = line->next_sibling();
		}
		else
		{
			l = 0;
		}

		for (int j = 0; j < XMAP; j++)
		{
			water->set(XMAP - j - 1, i, l % 2);
			l /= 2;
		}
	}
	water->update();
}